import { defineStore } from 'pinia'
import {
  codeSubmitRequest,
  getSupportCodeRequest,
  codeCompileRequest
} from '@/api/Desktop/code/index.js'
const codeStore = defineStore('codeStore', {
  state: () => ({
    codeContent: '',
    supportLanguages: [],
    Currentlanguages: 'javascript',
    passCompile: false,
    TerminalMessage: [],
    passRun: false
  }),
  actions: {
    changeLanguage(language) {
      this.Currentlanguages = this.supportLanguages.filter(
        (item) => item == language
      )[0]
    },
    async getSupportCode() {
      const res = await getSupportCodeRequest()
      this.supportLanguages = [
        ...new Set([...this.supportLanguages, ...res.data.data])
      ]
    },
    async codeCompile(code) {
      if (this.codeContent) {
        const { data: compileStatus } = await codeCompileRequest(
          code,
          this.Currentlanguages
        )
        if (compileStatus.data.success) {
          this.passCompile = compileStatus.data.success
        } else {
          this.passCompile = false
          this.TerminalMessage.push({
            errorMessage: compileStatus.data.errorMessage.replace(/\\n/g, ''),
            time: new Date().toLocaleString(),
            status: this.passCompile
          })
        }
      }
    },
    async runCode() {
      if (this.codeContent) {
        const { data: runSatus } = await codeSubmitRequest(
          this.codeContent,
          this.Currentlanguages
        )
        if (runSatus.data.success) {
          this.passRun = true
          this.TerminalMessage.push({
            runValues: runSatus.data.message,
            time: new Date().toLocaleString(),
            status: this.passRun
          })
        } else {
          this.passRun = false
          this.TerminalMessage.push({
            errorMessage: runSatus.data.errorMessage.replace(/\\n/g, ''),
            time: new Date().toLocaleString(),
            status: this.passRun
          })
        }
      }
    }
  }
})
export default codeStore
